// 为杭州商城订制的登录注册多语种页面
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Button, List, InputItem, Switch, Modal, ActivityIndicator } from "antd-mobile";
import MToast from "../../components/Util/MToast"
import { routerRedux } from "dva/router";
import { createForm } from 'rc-form';
import { isNull,goToPage } from "../../utils/helper";
import { VCODE } from "../../config/Config";
import md5 from "md5";
import "./Login.less";
import {IntlProvider, addLocaleData,FormattedMessage} from 'react-intl';
import localeData from '../../../public/lang/data.json';
import { Row, Col,Select } from 'antd';
import 'antd/dist/antd.css'; // or 'antd/dist/antd.less'
import MLoading from '../../components/Util/MLoading';
import { getParmaFromUrl } from '../../utils/request';

@connect(() => {
	return ({})
})
@createForm()
export default class NewLogin extends PureComponent {
	constructor(props) {
		super(props);
		this.timer = "";
		this.state = {
			formData: {
				username: "",
				password: ""
			},
			loading: false,
			getTokenResult: {},
			codeSrc: "",
      privacyModal:false
		}
	}

	componentWillMount() {
		document.title = localStorage[MI_APP_CODE + "website"] + " - " + "登录";
		let { dispatch, location } = this.props;
    if(localStorage.locale=='it'){
      localStorage.setItem("locale",'it')
    }else if(localStorage.locale=='zh'){
      localStorage.setItem("locale",'zh')

    }else{
      localStorage.setItem("locale",'it')

    }
    dispatch({
      type: "login/getToken",
      payload: {
        callback: (result) => {
          let { data } = result;
          this.setState({
            getTokenResult: data
          })
          document.title = localStorage[MI_APP_CODE + "website"] + " - " + "登录";
        }
      }
    });

	}
  login = () => {
    let { dispatch, history } = this.props;
    const { validateFields, setFieldsValue } = this.props.form;
    const loginSuccess = (result) => {
      localStorage.removeItem(MI_APP_CODE + localStorage[MI_APP_CODE + "mi_token"]);
      let { user_name, user_id, menus, permissions, default_page, role_id } = result.data;
      localStorage[MI_APP_CODE + "username"] = user_name;
      localStorage[MI_APP_CODE + "user_id"] = user_id;
      localStorage[MI_APP_CODE + "role_id"] = role_id;
      localStorage[MI_APP_CODE + "menus"] = JSON.stringify(menus);
      localStorage[MI_APP_CODE + "permissions"] = permissions;
      MToast.success(localeData[localStorage.locale].loginSuccess, 0.8);
      setTimeout(() => {
        // window.location.reload();
        goToPage({ dispatch, config: { url: "/shop_home" }, })
      }, 1000)
    };
    validateFields((err, value) => {
      let { username, password, remember, code } = value;
      if (isNull(username)) {
        MToast.fail(localeData[localStorage.locale].loginUsername, 2, null, false)
      }
      else if (isNull(password)) {
        MToast.fail(localeData[localStorage.locale].loginPassword, 2, null, false)
      }
      else if (this.showCode() && isNull(code)) {
        MToast.fail(localeData[localStorage.locale].loginCode1, 2, null, false)
      }
      else {
        this.setState({
          loading: true
        });
        let obj = {
          username,
          password: md5(password),
          go_on: 0,
          remember: remember ? 1 : 0
        };
        if (this.showCode()) {
          obj.code = code;
        }
        dispatch({
          type: "login/login",
          payload: {
            ...obj,
            callback: (result) => {
              let { code, msg } = result;
              if (code == 10200) {
                // console.log("登陆成功");
                console.log(result);
                loginSuccess(result);
              }
              else if (code == 10306) {
                // console.log("强制需要修改密码，弹窗，确认跳转修改密码页面，取消就停留当前页面");
                MToast.info(localeData[localStorage.locale].loginPassword2)
              }
              else if (code == 10311) {
                // console.log("弹窗建议修改密码，确认跳转页面，取消 跳转首页");
                MToast.info(localeData[localStorage.locale].loginPassword3)
              }
              else if (code == 10406) {
                // console.log("用户已登陆 弹窗提示是否继续 确认 go_on改为1 继续提交");
                Modal.alert(localeData[localStorage.locale].loginInfo, msg, [
                  { text: localeData[localStorage.locale].myModelCancel },
                  {
                    text: localeData[localStorage.locale].myModelSure, onPress: () => {
                    obj = {
                      ...obj,
                      go_on: 1
                    };
                    dispatch({
                      type: "login/login",
                      payload: {
                        callback: (result) => {
                          if (result.code == 10200) {
                            // console.log("登陆成功");
                            this.setState({
                              tips: result.msg
                            })
                            loginSuccess(result);
                          }
                        }
                      }
                    })
                  }
                  },
                ])
              }
              else if (code == 10404) {
                this.changeCode();
                let token = localStorage[MI_APP_CODE + "mi_token"];
                localStorage[MI_APP_CODE + token] = 1;
                setFieldsValue({
                  code: undefined
                })
                MToast.fail(msg, 2, null, false)
              }
              else if (code == 10403 || code == 10401) {
                // console.log("输入验证码错误 验证码过期  更换验证码");
                this.changeCode();
                let token = localStorage[MI_APP_CODE + "mi_token"];
                localStorage[MI_APP_CODE + token] = 1;
                setFieldsValue({
                  code: undefined
                })
                MToast.fail(msg, 2, null, false)
              }
              else if (code == 10104 || code == 10105) {
                // console.log("token不存在或过期 原来token删除 重新获取token 不提示用户 重新调用登陆");
                dispatch({
                  type: "mlogin/changeToken",
                  payload: {
                    callback: () => {
                      this.handleSubmit()
                    }
                  }
                })
              }
              else {
                MToast.fail(msg, 2, null, false)
              }
              this.setState({
                loading: false
              })
            }
          }
        })
      }
    })
  }
  changeCode() {
    setTimeout(() => {
      this.setState({
        codeSrc: API_URL + VCODE + localStorage[MI_APP_CODE + "mi_token"] + "&r=" + Math.random() + "&type=login"
      })
    }, 100)
  }
  showCode = () => {
    let mi_token = localStorage[MI_APP_CODE + "mi_token"];
    if (localStorage[MI_APP_CODE + mi_token] == 1) {
      return true
    }
    else {
      return false
    }
  }
	goRegister(){
		let {dispatch}=this.props;
		dispatch(routerRedux.push("/register"))
	}
	render() {

		let { dispatch } = this.props;
		let { formData, getTokenResult, codeSrc,privacyModal } = this.state;
		let { logo, name, copyright, title } = getTokenResult;
		const { getFieldProps } = this.props.form;
    const messages = localeData[localStorage.locale]
		return (
      <IntlProvider
        locale={ localStorage.locale } messages={messages}
      >
        <div className="login-box">
          <div className="logo">
            <img src={logo} alt="" /><br />
            <p style={{ fontSize: "1.2rem", paddingTop: "0.5rem" }}>
              {title}
            </p>
          </div>
          <div className="content" style={{margin:'20px'}}>
            <div style={{border:'1px solid #EEEDF2',borderRadius:'5px',position:'relative',marginBottom:'25px'}}>
              <div style={{color:'#9C9BAB',fontSize:'11px',position:'absolute',top:'-19px',left:'23px',zIndex:'10',background:'#fff',padding:'8px'}}>{messages.loginUsername1}</div>
              <InputItem style={{paddingTop:'20px'}}
                labelNumber="3"
                {...getFieldProps('username', {
                  rules: [
                    { required: true }
                  ]
                })}
                placeholder={messages.loginUsername}
                clear
              ><div style={{paddingTop:'20px'}}><img src="image/login_user.png" alt="" /></div></InputItem>
            </div>
            <div style={{border:'1px solid #EEEDF2',borderRadius:'5px',position:'relative',marginBottom:'25px'}}>
              <div style={{color:'#9C9BAB',fontSize:'11px',position:'absolute',top:'-19px',left:'23px',zIndex:'10',background:'#fff',padding:'8px'}}>{messages.loginPassword1}</div>
              <InputItem style={{paddingTop:'20px'}}
                labelNumber="3"
                {...getFieldProps('password')}
                placeholder={messages.loginPassword}
                type="password"
                clear
              ><div style={{paddingTop:'20px'}}><img src="image/login_password.png" alt="" /></div></InputItem>
            </div>
            {
              this.showCode() && <div data-flex="fir:left box:last cross:center" className="vcode">
                <div style={{border:'1px solid #EEEDF2',borderRadius:'5px',position:'relative',marginBottom:'25px'}}>
                  <div style={{color:'#9C9BAB',fontSize:'11px',position:'absolute',top:'-19px',left:'23px',zIndex:'10',background:'#fff',padding:'8px'}}>{messages.loginPassword1}</div>
                  <InputItem style={{paddingTop:'20px'}}
                    {...getFieldProps('code')}
                    placeholder={messages.loginCode}
                    clear
                  />

                </div>
                <img onClick={() => this.changeCode()} src={codeSrc} alt="" style={{marginTop:'-24px'}}/>
              </div>
            }
            <Button
              loading={this.state.loading}
              style={{background:'#F09600',borderRadius:'20px',border:'none',height:'42px',lineHeight:'42px'}}
              type="primary"
              onClick={() => this.login()}
             >{messages.login}</Button>

            <Button
              style={{background:'#F0F2F5',borderRadius:'20px',border:'none',height:'42px',lineHeight:'42px'}}
              onClick={() =>{this.setState({
                privacyModal:true
              })}}
              >{messages.register}</Button>
          </div>
          <Modal
            visible={this.state.privacyModal}
            style={{width:'98%'}}
            transparent
            maskClosable={false}
            title={messages.privacyTitle}
            footer={[{ text:messages.privacyDisagree, onPress: () => this.setState({privacyModal:false}) },
              { text: messages.privacyAgree, onPress: () => this.goRegister() },]}
          >
            <div style={{ height:500, overflow: 'scroll',color:'#606266',fontSize:'14px',textAlign:'left'}}>
              <div style={{marginBottom:'20px'}}>{messages.privacy1}</div>
              <div style={{marginBottom:'20px'}}>{messages.privacy2}</div>
              <div style={{color:'#303133',marginBottom:'20px'}}>{messages.privacy3}</div>
              <div style={{marginBottom:'20px'}}>{messages.privacy4}</div>
              <div style={{marginBottom:'20px'}}>{messages.privacy5}</div>
              <div style={{color:'#303133',marginBottom:'20px'}}>{messages.privacy6}</div>
              <div style={{marginBottom:'20px'}}>{messages.privacy7}</div>
              <div style={{marginBottom:'20px'}}>{messages.privacy8}</div>
              <div style={{marginBottom:'20px'}}>{messages.privacy9}</div>
              <div style={{marginBottom:'20px'}}>{messages.privacy10}</div>
              <div style={{marginBottom:'20px'}}>{messages.privacy11}</div>
              <div style={{color:'#303133',marginBottom:'20px'}}>{messages.privacy12}</div>
              <div style={{marginBottom:'20px'}}>{messages.privacy13}</div>
              <div style={{color:'#303133',marginBottom:'20px'}}>{messages.privacy14}</div>
              <div style={{marginBottom:'20px'}}>{messages.privacy15}</div>
              <div style={{color:'#303133',marginBottom:'20px'}}>{messages.privacy16}</div>
              <div style={{marginBottom:'20px'}}>{messages.privacy17}</div>
              <div style={{marginBottom:'20px'}}>{messages.privacy18}</div>
              <div style={{marginBottom:'20px'}}>{messages.privacy19}</div>
              <div style={{marginBottom:'20px'}}>{messages.privacy20}</div>
              <div style={{marginBottom:'20px',textAlign:'right'}}>{messages.privacy21}</div>
            </div>
          </Modal>
        </div>
      </IntlProvider>
		)
	}
}
